package com.gugee.ins.data.blogger.es.core;

import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.ins.common.dal.service.blogger.InsBloggerMainDao;
import com.gugee.ins.common.model.es.blogger.InsBlogger;
import com.gugee.ins.common.model.mysql.blogger.InsBloggerMain;
import com.gugee.ins.data.blogger.es.config.BloggerToElasticsearchAppConfig;
import com.gugee.ins.data.common.msg.InsBloggerMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

@Slf4j
public abstract class EsBaseService {
    String workName;
    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    @Autowired
    BloggerToElasticsearchAppConfig bloggerToElasticsearchAppConfig;

    @Autowired
    InsBloggerMainDao insBloggerMainDao;

    ForkJoinPool forkJoinPool = ThreadPoolUtils.forkJoinPool(10,"defaultThreadPool");


    public void handler(List<InsBloggerMessage> insBloggerMessages) {
        List<Long> ids = new ArrayList<>(insBloggerMessages.size());
        insBloggerMessages.forEach(x -> ids.add(x.getUid()));
        List<InsBloggerMain> insBloggers = insBloggerMainDao.findInUid(ids);
        List<InsBlogger> esInsBloggers = new ArrayList<>(insBloggers.size());
        try{
            forkJoinPool.submit(()->insBloggers.parallelStream().forEach(insBloggerMain -> {
                try{
                    esInsBloggers.add(structureEsBlogger(insBloggerMain));
                }catch (Exception e){
                    log.error("{} error! uid:{},{}",workName,insBloggerMain.getUid(),e);
                }
            })).get();
        }catch (Exception e){
            log.error("{} error!",workName,e);
        }

        try{
            toEsHandler(bloggerToElasticsearchAppConfig.getBloggerIndex(),esInsBloggers);
        }catch (Exception e){
            log.error("{} to es error!",workName,e);
        }

    }

    /**
     * 构造ES播主对象
     * @return
     */
    protected abstract InsBlogger structureEsBlogger(InsBloggerMain insBloggerMain);

    /**
     * 同步ES的处理
     * @param esIndex
     * @param insBloggers
     */
    protected abstract void toEsHandler(String esIndex,List<InsBlogger> insBloggers);
}
